package org.kumas.sgrpc.remoting.utils;

import org.kumas.sgrpc.common.URL;
import org.kumas.sgrpc.remoting.Constants;

import static org.kumas.sgrpc.common.constants.CommonConstants.GROUP_KEY;
import static org.kumas.sgrpc.common.constants.CommonConstants.INTERFACE_KEY;
import static org.kumas.sgrpc.common.constants.CommonConstants.VERSION_KEY;
import static org.kumas.sgrpc.common.constants.RegistryConstants.REGISTRY_PROTOCOL;
import static org.kumas.sgrpc.common.constants.RegistryConstants.SERVICE_REGISTRY_PROTOCOL;

public class UrlUtils {
    public static int getIdleTimeout(URL url) {
        int heartBeat = getHeartbeat(url);
        // idleTimeout should be at least more than twice heartBeat because possible retries of client.
        int idleTimeout = url.getParameter(Constants.HEARTBEAT_TIMEOUT_KEY, heartBeat * 3);
        if (idleTimeout < heartBeat * 2) {
            throw new IllegalStateException("idleTimeout < heartbeatInterval * 2");
        }
        return idleTimeout;
    }

    public static int getHeartbeat(URL url) {
        return url.getParameter(Constants.HEARTBEAT_KEY, Constants.DEFAULT_HEARTBEAT);
    }

    public static boolean isRegistry(URL url) {
        return REGISTRY_PROTOCOL.equals(url.getProtocol()) || SERVICE_REGISTRY_PROTOCOL.equalsIgnoreCase(url.getProtocol());
    }

    public static boolean isServiceKeyMatch(URL pattern, URL value) {
        return pattern.getParameter(INTERFACE_KEY).equals(
            value.getParameter(INTERFACE_KEY))
            && isItemMatch(pattern.getParameter(GROUP_KEY),
            value.getParameter(GROUP_KEY))
            && isItemMatch(pattern.getParameter(VERSION_KEY),
            value.getParameter(VERSION_KEY));
    }

    static boolean isItemMatch(String pattern, String value) {
        if (pattern == null) {
            return value == null;
        } else {
            return "*".equals(pattern) || pattern.equals(value);
        }
    }
}